package com.qujia.station.task;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qujia.station.domain.EnterpriseGrowUpValueSetting;
import com.qujia.station.service.IEnterpriseGrowUpValueSettingService;
import com.qujia.system.service.IAppUserInfoUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * @date 2024/1/15
 */
@Component
public class GrowUpValueTask {

    private static final Logger log = LoggerFactory.getLogger(GrowUpValueTask.class);

    private static final Object[][] MONTH_LAST_DAYS = new Object[][]{
            new Object[]{"31"},
            new Object[]{"30","31"},
            new Object[]{"29","30","31"},
            new Object[]{"28","29","30","31"},
    };

    @Autowired
    private IEnterpriseGrowUpValueSettingService enterpriseGrowUpValueSettingService;
    @Autowired
    private IAppUserInfoUserService appUserInfoUserService;

    @Scheduled(cron = "0 0 * * * *")
    public void scheduledResetUserGrowValueTask(){
        log.info("重置用户成长值定时任务====开始");
        LocalDateTime now = LocalDateTime.now();
        LocalDate localDate = now.toLocalDate();
        int lastDayMonth = localDate.lengthOfMonth();
        int month = localDate.getDayOfMonth();
        EnterpriseGrowUpValueSetting form = new EnterpriseGrowUpValueSetting();
        form.setExpireMode(2);
        form.setTimeOfDay(LocalTime.of(now.getHour(), 0, 0));
        LambdaUpdateWrapper<EnterpriseGrowUpValueSetting> qw = Wrappers.lambdaUpdate(form);
        if (month == lastDayMonth && month < 31) {
            qw.in(EnterpriseGrowUpValueSetting::getDayOfMonth, MONTH_LAST_DAYS[31 - month]);
        } else {
            form.setDayOfMonth(String.valueOf(month));
        }
        List<EnterpriseGrowUpValueSetting> list = enterpriseGrowUpValueSettingService.list(qw);
        for (EnterpriseGrowUpValueSetting setting : list) {
            if (setting.getEnterpriseId() == null) {
                continue;
            }
            log.info("重置用户成长值定时任务====油企id:[{}]",setting.getEnterpriseId());
            appUserInfoUserService.resetUserGrowUpValue(setting.getEnterpriseId());
        }
    }

}
